package login;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {
	private String username, password, errorMsg, user_role="", link="", msg, AccountStatus;
	private HttpSession session;
	private Entity user;

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {

		this.session = req.getSession(true);
		errorMsg = ValidateLoginData(req.getParameter("username"), req.getParameter("password"));
		
		if(errorMsg != "pass")
		{
			 this.link="login.jsp";
			 Msg(resp,"Login Error",this.errorMsg,this.link,"warning.png");
		}
		else
		{
			DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
			
			Key accountKey = KeyFactory.createKey("Accounts", "accountName");
			
			Query query = new Query("Account", accountKey).addFilter("username", FilterOperator.EQUAL, this.username);
			this.user = datastore.prepare(query).asSingleEntity();
			
			//Checking login data
			if (this.password.equals(this.user.getProperty("password").toString())) {
				this.user_role = this.user.getProperty("account_type").toString();	//getting the user role
				this.AccountStatus = this.user.getProperty("lockStatus").toString();	//Getting the current account status
				
				this.CheckAccountStatus(resp);			//Checking account status (locked / unlocked)
				} else {
				this.msg = "Incorrect login details. Please enter the correct login details and try again. Click on Continue ";
				Msg(resp, "LOGIN ERROR - INCORRECT LOGIN DETAILS",this.msg,"login.jsp","warning.png");
			}
		}
	}
	
	public String ValidateLoginData(String username, String password)
	{
		String errorMsg = "pass";
		
		if(!username.equals("")) {
			setUsername(username);
		} else {
			this.errorMsg = "Username cannot be blank";
			return errorMsg;
		}
		
		if(!password.equals("")) {
			setPassword(password);
		} else {
			this.errorMsg = "Password cannot be blank";
			return errorMsg;
		}
		
		if(username.equals("") && password.equals(""))
			this.errorMsg = "Username & Password cannot be blank";
		
		return errorMsg;
	}
	
	private void CheckAccountStatus(HttpServletResponse resp) throws IOException{
		if(this.AccountStatus.equals("Locked")){
			this.msg = "Your account has been locked by system administrator. Please contact system administrator to resolve this issue.";
			Msg(resp, "LOGIN ERROR - ACCOUNT STATUS",this.msg,"login.jsp","warning.png");
		}
		
		if(this.AccountStatus.equals("Unlocked")){
			LoggingIn(resp);		//logging into the system
		}
	}
	
	private void CreateSessionVariables(Entity user, HttpSession session)
	{
		session.setAttribute("username", user.getProperty("username"));
		session.setAttribute("firstName", user.getProperty("firstName"));
		session.setAttribute("lastName", user.getProperty("lastName"));
		session.setAttribute("account_type", user.getProperty("account_type"));
	}
	
	private void LoggingIn(HttpServletResponse resp) throws IOException
	{
		//configuring the login according to user role
		if (this.user_role.equals("user"))
			this.link = "home.jsp";
		
		if (this.user_role.equals("admin"))
			this.link = "adminInterface.jsp";
		
		//Login Success Message
		if(this.user_role.equals("user") || this.user_role.equals("admin")){
			CreateSessionVariables(user, this.session);		//Creating Session Variables
			this.msg = "Your have succesfully logged into Media Vault.";
			Msg(resp, "Hi " + this.user.getProperty("firstName").toString() + "!!", this.msg, this.link,"success.png");
		}
		else {
			this.msg = "Please contact system administrator to resolve this issue";
			this.link = "login.jsp";
			Msg(resp, "System Error", this.msg, this.link,"warning.png");
		}
	}
	
	private void Msg(HttpServletResponse resp, String Title, String content, String link, String image) throws IOException
	{
			resp.getWriter().println("<div id=\"loginMsgPanel\">" +
										"<div id=\"login_image\"><img src=\"images/"+image+"\" width\"95\" height=\"95\"/></div>" + 
										"<div id=\"login_msg\">" +
											"<label style=\"font-weight:bold;\">" + Title + "</label></br>" +
											"<label>" + content + "</br><a href=\""+ link +"\">Continue</a>" +
											"</label>" +
										"</div>" +
									"</div>");
	}
	
	private void setUsername(String username){
		this.username = username;
	}
	
	private void setPassword(String password){
		this.password = password;
	}
}
